package com.jinlejia.erp.base;


import android.content.Context;

import com.jinlejia.erp.bean.SaveCookieBean;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.DbUtil;

import java.io.IOException;
import java.lang.reflect.Field;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网咯请求拦截器
 * 添加token和cookie
 */
public class NetInterceptor implements Interceptor {
    private Context context;
    private final boolean debug;
    public NetInterceptor(Context c) {
        this.context = c;
        debug = checkDebug();
    }

    private boolean checkDebug(){
        boolean isDebug;
        try {
            String packageName = context.getPackageName();
            Class buildConfig = Class.forName(packageName + ".BuildConfig");
            Field DEBUG = buildConfig.getField("DEBUG");
            DEBUG.setAccessible(true);
            isDebug = DEBUG.getBoolean(null);
        } catch (Throwable t) {
            isDebug = false;
        }
        return isDebug;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if ("www.pgyer.com".equals(request.url().host())){ //如果是蒲公英，则不进行拦截
            return chain.proceed(request);
        }
        HttpUrl url = request.url();
        if (!debug){ //如果是发布版本
            String newUrl = url.toString().replace(ApiConfig.IP(),"https://api.jinlejia.com/");
            url = HttpUrl.parse(newUrl);
        }
        request = request.newBuilder()
                .url(url)
                .addHeader("token", ACache.get(context).getAsString("token") == null ? "" : ACache.get(context).getAsString("token"))
                .addHeader("cookie",  null == DbUtil.getDB(context).single().queryById(200,SaveCookieBean.class)  ? "" : DbUtil.getDB(context).single().queryById(200, SaveCookieBean.class).getCookie())
                .build();

        return chain.proceed(request);
    }
}
